
<template>
  <div class="member-management">  
    <!-- 搜索区域 -->  
    <el-card class="box-card operation-container" shadow="never">  
      <el-form :inline="true" @submit.prevent="handleSearch">  
        <el-form-item label="搜索">  
          <el-input 
            v-model="searchKeyword" 
            placeholder="输入用户名、手机号、邮箱进行搜索" 
            clearable
            style="width: 300px;"
            @keyup.enter="handleSearch"
            @clear="handleClear">
            <template #prepend>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>  
        </el-form-item>
        
        <el-form-item label="性别">  
          <el-select 
            v-model="queryParams.gender" 
            placeholder="全部" 
            clearable
            style="width: 120px;">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>  
        </el-form-item>
        
        <el-form-item>  
          <el-button type="primary" @click="handleSearch">  
            查询  
          </el-button>
          <el-button @click="handleReset">  
            重置  
          </el-button>  
        </el-form-item>  
      </el-form>  
    </el-card>  

    <!-- 表格区域 -->
    <el-card class="box-card table-container" shadow="never">  
      <!-- 显示当前搜索状态 -->
      <div v-if="searchKeyword || queryParams.gender" class="search-tips">
        <el-tag closable @close="clearSearch" type="info">
          {{ getSearchTip() }}
        </el-tag>
      </div>
      
      <el-table :data="tableData" style="width: 100%" border v-loading="loading">  
        <el-table-column prop="userId" label="用户ID" width="80" align="center" />
        <el-table-column prop="username" label="用户名" width="120" align="center" />  
        <el-table-column prop="gender" label="性别" width="80" align="center" />  
        <el-table-column prop="phone" label="手机" width="140" align="center" />  
        <el-table-column prop="userEmail" label="邮箱" width="180" align="center" />
        <el-table-column prop="registerTime" label="加入时间" width="160" align="center" />  
        <el-table-column prop="level" label="等级" width="100" align="center" />
        <el-table-column prop="userStatus" label="用户状态" width="100" align="center">
          <!-- 修正 #1：状态显示逻辑 -->
          <template #default="scope">
            <el-tag :type="scope.row.userStatus === 1 ? 'success' : 'danger'" disable-transitions>
               {{ scope.row.userStatus === 1 ? '启用' : '禁用' }}
            </el-tag>
         </template>
        </el-table-column>
        <el-table-column label="操作" width="120" fixed="right" align="center">  
          <template #default="scope">  
            <el-button type="primary" :icon="Edit" size="small" circle @click="handleEdit(scope.row)" />  
            <el-button type="danger" :icon="Delete" size="small" circle @click="handleDelete(scope.row)" />  
          </template>  
        </el-table-column>  
      </el-table>  

      <!-- 分页区域 -->  
      <div class="pagination-container" v-if="total > 0">  
        <el-pagination  
            background  
            layout="total, sizes, prev, pager, next, jumper"  
            :total="total"
            :page-sizes="[5, 10, 15, 20]"
            v-model:current-page="queryParams.page"  
            v-model:page-size="queryParams.pageSize"  
            @current-change="handlePageChange"
            @size-change="handleSizeChange"
        />  
      </div>  
    </el-card>

    <!-- 编辑用户弹窗 -->
    <el-dialog v-model="editDialogVisible" title="编辑用户" width="600px" @close="resetForm">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="80px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="editForm.gender">
            <el-radio label="男">男</el-radio>
            <el-radio label="女">女</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="手机" prop="phone">
          <el-input v-model="editForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="邮箱" prop="userEmail">
          <el-input v-model="editForm.userEmail" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="editForm.address" type="textarea" placeholder="请输入地址" />
        </el-form-item>
        <el-form-item label="等级" prop="level">
          <el-select v-model="editForm.level" placeholder="请选择等级" style="width: 100%;">
            <el-option label="普通" value="普通" />
            <el-option label="白银" value="白银" />
            <el-option label="黄金" value="黄金" />
            <el-option label="白金" value="白金" />
            <el-option label="钻石" value="钻石" />
          </el-select>
        </el-form-item>
        <!-- 弹窗中也需要更新状态的显示和绑定 -->
        <el-form-item label="用户状态" prop="userStatus">
            <el-switch
                v-model="editForm.userStatus"
                :active-value="1"
                :inactive-value="0"
                active-text="启用"
                inactive-text="禁用"
            />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="editDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitEditForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

  </div>  
</template>  

<script setup>  
import { ref, reactive, onMounted } from 'vue';  
import { Search, Edit, Delete } from '@element-plus/icons-vue';  
import request from '../../util/request.js'
import { ElMessage, ElMessageBox } from 'element-plus';  

// --- 响应式状态 ---  
const loading = ref(true);   
const searchKeyword = ref(''); 

const queryParams = reactive({  
  page: 1,  
  pageSize: 10,
  username: '',
  phone: '',
  userEmail: '',
  gender: '',
});  

const tableData = ref([]);  
const total = ref(0);  

// --- 编辑用户弹窗 ---
const editDialogVisible = ref(false);
const editFormRef = ref(null);
const editForm = ref({});

const editFormRules = reactive({
  username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
  gender: [{ required: true, message: '请选择性别', trigger: 'change' }],
  phone: [
    { required: true, message: '请输入手机号', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '手机号格式不正确', trigger: 'blur' }
  ],
  userEmail: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '邮箱格式不正确', trigger: 'blur' }
  ],
  level: [{ required: true, message: '请选择等级', trigger: 'change' }],
  userStatus: [{ required: true, message: '请选择用户状态', trigger: 'change' }]
});


// --- 智能搜索逻辑 ---
const processSearchKeyword = () => {
  queryParams.username = '';
  queryParams.phone = '';
  queryParams.userEmail = '';
  if (!searchKeyword.value.trim()) return;
  const keyword = searchKeyword.value.trim();
  if (/^1[3-9]\d{9}$/.test(keyword)) {
    queryParams.phone = keyword;
  } else if (keyword.includes('@') && /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(keyword)) {
    queryParams.userEmail = keyword;
  } else {
    queryParams.username = keyword;
  }
};

const getSearchTip = () => {
  let tips = [];
  if (searchKeyword.value) {
    if (queryParams.phone) tips.push(`手机号: ${queryParams.phone}`);
    else if (queryParams.userEmail) tips.push(`邮箱: ${queryParams.userEmail}`);
    else if (queryParams.username) tips.push(`用户名: ${queryParams.username}`);
  }
  if (queryParams.gender) tips.push(`性别: ${queryParams.gender}`);
  return tips.join(' | ');
};

// --- 核心功能：API调用 ---  
const fetchUserList = async () => {  
  loading.value = true;  
  try {  
    const response = await request.get('/admin/user/list', { params: queryParams });  
    if (response.data && response.data.code === 1) {  
      tableData.value = response.data.data.records;  
      total.value = response.data.data.total;  
    } else {  
      ElMessage.error(response.data.msg || '数据加载失败');  
    }  
  } catch (error) {  
    console.error("请求用户列表时出错:", error);  
    ElMessage.error('网络连接失败或服务器错误');  
  } finally {  
    loading.value = false;  
  }  
};  

// --- 事件处理 ---  
const handleSearch = () => {  
  processSearchKeyword();
  queryParams.page = 1;
  fetchUserList();  
};  

const handleReset = () => {
  searchKeyword.value = '';
  queryParams.username = '';
  queryParams.phone = '';
  queryParams.userEmail = '';
  queryParams.gender = '';
  queryParams.page = 1;
  fetchUserList();
};

const handleClear = () => {
  searchKeyword.value = '';
  queryParams.username = '';
  queryParams.phone = '';
  queryParams.userEmail = '';
  handleSearch();
};

const clearSearch = () => {
  handleReset();
};

const handleEdit = async (row) => {
  editDialogVisible.value = true;
  try {
    const res = await request.get(`/admin/user/${row.userId}`);
    if (res.data && res.data.code === 1) {
      editForm.value = res.data.data;
    } else {
      ElMessage.error(res.data.msg || '获取用户信息失败');
    }
  } catch (error) {
    ElMessage.error('网络错误，无法获取用户信息');
  }
};

const submitEditForm = () => {
  editFormRef.value.validate(async (valid) => {
    if (valid) {
      try {
        const res = await request.put('/admin/user/update', editForm.value);
        if (res.data && res.data.code === 1) {
          ElMessage.success('用户信息更新成功');
          editDialogVisible.value = false;
          fetchUserList();
        } else {
          ElMessage.error(res.data.msg || '更新失败');
        }
      } catch (error) {
        console.error("更新用户信息失败:", error);
        ElMessage.error('网络错误，更新失败');
      }
    } else {
      return false;
    }
  });
};

const resetForm = () => {
  if (editFormRef.value) {
    editFormRef.value.resetFields();
  }
  editForm.value = {};
};

const handleDelete = (row) => {
  // 1. 确定将要提交的新状态
  const newStatus = row.userStatus === 1 ? 0 : 1; 
  const actionText = row.userStatus === 1 ? '禁用' : '启用';

  ElMessageBox.confirm(
    `确定要${actionText}用户 "${row.username}" 吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(async () => {
    try {
      const requestBody = {
        userId: row.userId,
        userStatus: newStatus
      };
      const res = await request.put('/admin/user/status', requestBody);
      
      if (res.data && res.data.code === 1) {
        ElMessage.success(`用户 "${row.username}" 已成功${actionText}`);
        // 4. 操作成功后，刷新表格数据
        fetchUserList(); 
      } else {
        ElMessage.error(res.data.msg || '操作失败');
      }
    } catch (error) {
      console.error("状态更新操作失败:", error);
      ElMessage.error('网络错误，操作失败');
    }
  }).catch(() => {
    ElMessage.info('已取消操作');
  });
};

const handlePageChange = (newPage) => {  
  queryParams.page = newPage;  
  fetchUserList();  
};  

const handleSizeChange = (newSize) => {
  queryParams.pageSize = newSize;
  queryParams.page = 1; 
  fetchUserList();
};

onMounted(() => {  
  fetchUserList();  
});  
</script>  

<style scoped>  
/* ... 样式保持不变 ... */
.member-management {  
  padding: 20px;  
}  

.operation-container {  
  margin-bottom: 20px;  
}  

.el-form-item {  
  margin-bottom: 0;  
}  

.search-tips {
  margin-bottom: 16px;
}

.search-tips .el-tag {
  margin-right: 8px;
}

.pagination-container {  
  display: flex;  
  justify-content: flex-end;  
  margin-top: 20px;  
}  

:deep(.el-input-group__prepend) {
  background-color: #f5f7fa;
}

:deep(.el-pagination) {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}

:deep(.el-pagination .el-select .el-input) {
  width: 100px;
}
</style>
